<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>组件访问-父组件直接访问子组件($children)</title>
  <style>
    #app {
      margin-top: 50px;
      text-align: center;
    }

    button {
      margin-top: 20px;
      padding: 10px;
    }
  </style>
</head>

<body>

  <div id="app">
    <cpn></cpn>
    <cpn></cpn>
    <cpn ref="myCpn"></cpn>
    <div>
      <button @click="btnClick">执行第一个子组件方法，并获得name属性</button>
    </div>
    <div>
      <button @click="btnAllClick">执行所有</button>
    </div>
  </div>

  <template id="cpn">
    <div>
      <h3>我是子组件</h3>
    </div>
  </template>

  <script src="../../js/vue.js"></script>
  <script>
    const app = new Vue({
      el: '#app',
      components: {
        cpn: {
          template: '#cpn',
          data() {
            return {
              name: "Mr.chen",
              content: "我是内容"
            }
          },
          methods: {
            showMessage() {
              console.log("我是子组件里面的showMessage");
            }
          }
        }
      },

      methods: {
        btnClick() {
          let sonComponent = this.$children;
          // 试图访问子组件的methods方法
          console.log(sonComponent);
          // 执行第一个子组件的方法
          sonComponent[0].showMessage();
          // 打印第一个子组件的属性值
          console.log("第一个子组件的name属性值", sonComponent[0].name);

          // 通过 this.$refs 获取指定子组件信息，默认是一个空对象
          console.log("this.$refs获取", this.$refs.myCpn.name);
        },

        // 执行所有
        btnAllClick() {
          let sonComponent = this.$children;
          sonComponent.filter((item, index) => {
            item.showMessage();
            console.log(`${index} ${item.name}`);
          })
        }
      }
    })
  </script>
</body>

</html>